import React, {useState} from 'react';
import { PullToRefresh, Toast } from 'antd-mobile';

// props 类型定义
interface CommonPullToRefreshProps {
    onRefresh: () => Promise<void>; // 刷新时的回调，返回Promise
    hideOnRefresh?: React.ReactNode; // 下拉时隐藏的内容
    children: React.ReactNode; // 需要刷新的内容
}

const CommonPullToRefresh: React.FC<CommonPullToRefreshProps> = ({ onRefresh, hideOnRefresh, children }) => {
    const [hide, setHide] = useState(false);
    // 封装统一的下拉刷新逻辑
    const handleRefresh = async () => {
        setHide(true); //下拉时隐藏
        Toast.show({ icon: 'loading', content: '加载中...' });
        await onRefresh(); // 调用父组件传递的刷新函数
        setTimeout(() => {
            setHide(false); // 刷新完成，显示内容
            Toast.show({ icon:'success', content:'加载成功' });
        }, 0);
    }

    return (
        <PullToRefresh onRefresh={handleRefresh}>
            {!hide && hideOnRefresh}
            {children}
        </PullToRefresh>
    )
}

export default CommonPullToRefresh;